package com.lipy.ratelimit.atomic;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description: 原子计数器限流
 * @author: lipy
 * @create: 2020-07-19 22:13
 **/

public class AtomicLimit {
    private int maxCount = 10;
    private long interval = 6;
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    private long startTime = System.currentTimeMillis();

    public AtomicLimit() {
    }

    public AtomicLimit(int maxCount, long interval) {
        this.maxCount = maxCount;
        this.interval = interval;
    }

    public boolean limit(){
       return limit(maxCount, interval);
    }

    private boolean limit(int maxCount, long interval) {
        atomicInteger.addAndGet(1);

        if (atomicInteger.get() == 1){
            startTime = System.currentTimeMillis();
            return true;
        }

        if (System.currentTimeMillis() - startTime > interval){
            startTime = System.currentTimeMillis();
            atomicInteger.set(1);
            return true;
        }

        if(atomicInteger.get() > maxCount){

            return false;
        }
        return true;
    }

}
